import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.sun.jdi.ReferenceType;
import com.sun.tools.javac.util.List;


public class Reload {
	public void reloadClasses(List toReloads){
		Instrumentation vm;
		Map toReloadMap = new HashMap();
		for (Iterator iterator = toReloads.iterator(); iterator.hasNext();)
		{
		    String toReload = (String) iterator.next();
		    InputStream is = VMDebugger.class.getClassLoader().getResourceAsStream(toReload.replace('.', '/') + ".class");
		    if (is == null) {
		        throw new RuntimeException("Class " + toReload + " is not found in current classpath");
		    }
		    List classes = vm.classesByName(toReload);
		    if (classes == null || classes.isEmpty()) {
		        throw new RuntimeException("Class: " + toReload + " is not found in target JVM");
		    } else {
		        ReferenceType ref = (ReferenceType) classes.get();
		        try{
		            toReloadMap.put(ref, toByteArray(is));
		        }catch(Exception e){
		            e.printStackTrace();
		        }
		    }
		}
		vm.redefineClasses(toReloadMap);
  }
}
